<template>
  <div>
    <Category :disadled="!showList" />

    <el-card shadow="always" :body-style="{ padding: '20px' }" :style="{ marginTop: '20px' }" v-if="showList">
      <template #header>
        <el-button type="primary" icon="ele-Plus" @click="goAdd" :disabled="!category3Id">添加</el-button>
      </template>
      <el-table :data="attrList" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性名称" prop="attrName" width="150"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag type="warning" size="small" effect="light" v-for="attrValue in row.attrValueList" :key="attrValue.id"
              :style="{ marginRight: '5px' }">{{ attrValue.valueName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="{ row }">
            <el-tooltip content="修改" placement="top" effect="dark">
              <el-button type="warning" size="small" icon="ele-Edit" @click="EditAttr(row)"></el-button>
            </el-tooltip>

            <el-popconfirm title="你确定要删除吗?" @confirm="delAttr(row)">
              <template #reference>
                <span :style="{ marginLeft: '20px' }">
                  <el-tooltip content="删除" placement="top" effect="dark">
                    <el-button type="danger" size="small" icon="ele-Delete"></el-button>
                  </el-tooltip>
                </span>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="always" :body-style="{ padding: '20px 80px' }" :style="{ marginTop: '20px' }" v-else>
      <el-form label-width="80px" :inline="false" @submit.prevent="">
        <el-form-item label="属性名">
          <el-input v-model="attrInfo.attrName"></el-input>
        </el-form-item>
        <el-button type="primary" @click="addAttrValue" :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-table :data="attrInfo.attrValueList" border stripe :style="{ margin: '20px 0px' }">
          <el-table-column type="index" width="80" label="序号" />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input v-if="row.isShow" v-model="row.valueName" size="small" @blur="toLook(row, $index)"
                @keydown.enter="toLook(row, $index)" ref="inpEle"></el-input>
              <span v-else @click="goEdit(row)">
                {{ row.valueName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm title="确定要删除吗?" @confirm="delAttrValue($index)">
                <template #reference>
                  <el-button type="danger" size="default" icon="ele-Delete">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button type="warning" @click="goEdit(row)" icon="ele-Edit">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttr" :disabled="attrInfo.attrValueList.length === 0">保存</el-button>
        <el-button type="default" @click="showList = true">取消</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { cloneDeep } from "lodash";
import { nextTick, ref, watch } from "vue";
import { reqGetAttrInfo, reqAddAttrInfo, reqDelAttrInfo } from "@/api/attr";
import type { attrItemType, attrListType, attrValueItemType } from "@/api/attr";
import useCategoryStore from "@/stores/category";
import { storeToRefs } from "pinia";

const categoryStore = useCategoryStore();
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

const attrList = ref<attrListType>([]);

const getAttrList = async () => {
  try {
    const res = await reqGetAttrInfo(
      category1Id.value!,
      category2Id.value!,
      category3Id.value!
    );
    attrList.value = res;
  } catch (error: any) {
    ElMessage.error("平台属性获取失败:" + error.message);
  }
};

watch(
  category3Id,
  async () => {
    if (!category3Id.value) {
      attrList.value = [];
      return;
    }
    getAttrList();
  },
  {
    immediate: true,
  }
);
//
const showList = ref(true);
// 初始化添加数据
const attrInfo = ref<attrItemType>({
  attrName: "",
  attrValueList: [
    // {
    //   valueName: ""
    // }
  ],
  categoryId: null,
  categoryLevel: 3,
});
/**
 * 添加属性值时 编辑模式和查看模式的切换
 */
const goAdd = () => {
  showList.value = false;
  attrInfo.value = {
    attrName: "",
    attrValueList: [],
    categoryId: null,
    categoryLevel: 3,
  };
};
const inpEle = ref();
const addAttrValue = () => {
  attrInfo.value.attrValueList.push({ valueName: "", isShow: true });
  nextTick(() => {
    inpEle.value.focus();
  });
};
// 失去焦点  前往查看模式
const toLook = (row: attrValueItemType, index: number) => {
  row.isShow = false;
  // 判断是否为空
  if (!row.valueName) {
    attrInfo.value.attrValueList.splice(index, 1);
    ElMessage.error("属性值不能为空");
    return;
  }
  // 判断是否重复
  const isRepetition = attrInfo.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  if (isRepetition) {
    attrInfo.value.attrValueList.splice(index, 1);
    ElMessage.warning("属性值不能重复");
    return;
  }
};
// 点击前往编辑模式
const goEdit = (row: attrValueItemType) => {
  row.isShow = true;
  nextTick(() => {
    inpEle.value.focus();
  });
};

// 点击删除
const delAttrValue = (index: number) => {
  attrInfo.value.attrValueList.splice(index, 1);
  ElMessage.warning("删除成功");
};

// 点击保存
const saveAttr = async () => {
  attrInfo.value.attrValueList.forEach((item) => {
    delete item.isShow;
  });
  attrInfo.value.categoryId = category3Id.value;
  try {
    await reqAddAttrInfo(attrInfo.value);
    ElMessage.success("保存成功");
    showList.value = true;
    getAttrList();
  } catch (error: any) {
    ElMessage.error("保存失败" + error.message);
  }
};
// 修改
const EditAttr = (row: attrItemType) => {
  showList.value = false;
  /*
  用的是对象里的数组中的数据
  需要深拷贝
  */
  attrInfo.value = cloneDeep(row);
};
// 删除
const delAttr = async (row: attrItemType) => {
  try {
    await reqDelAttrInfo(row.id!);
    ElMessage.success("删除成功");
    getAttrList();
  } catch (error: any) {
    ElMessage.error("删除失败:" + error.message);
  }
};
</script>

<style scoped></style>
